package com.fiveGroup.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fiveGroup.annotation.Log;
import com.fiveGroup.pojo.Category;
import com.fiveGroup.pojo.vo.DataVo;
import com.fiveGroup.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

//分类信息管理控制层
@RestController
@RequestMapping("/api/classify")
@Slf4j
public class BackgroundCategoryController {
    @Autowired
    private CategoryService categoryService;

    //分页展示，模糊搜索,排序
    @GetMapping("/getCategories")
    public DataVo getCategories(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "5") Integer pageSize,
            @RequestParam(name = "name", required = false) String name) {
        IPage<Category> categoryIPage = new Page<>(page, pageSize);
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        log.info(name);
        //name不为空才去条件查询
        if (StringUtils.hasText(name)) {
            queryWrapper.like("name", name);
        }
        //按 sort 字段 升序排序（数字越小越靠前）
        queryWrapper.orderByAsc("sort");
        categoryService.page(categoryIPage, queryWrapper);
        return DataVo.success(categoryIPage);
    }

    //新增分类信息
    @PostMapping("/addCategories")
    @Log(action = "分类管理公告", detail = "新增分类信息")
    public DataVo addCategories(@RequestBody Category category) {
        //名称不能重复，不能为空
        if (!StringUtils.hasText(category.getName())) {
            return DataVo.fail("分类名称不能为空！");
        }

        //通过名字去数据库中的名字比对，不能重复
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getName, category.getName());
        Category existingCategory = categoryService.getOne(queryWrapper);
        if (existingCategory != null) {
            return DataVo.fail("该分类信息已存在！");
        }

        //创建这个分类的当前时间
        Date now = new Date();
        category.setCreatedAt(now);
        boolean saved = categoryService.save(category);
        if (saved) {
            return DataVo.success(category);
        } else {
            return DataVo.fail("新增分类失败，请重试");
        }
    }

    //单击删除分类信息
    @DeleteMapping("/deleteCategories/{id}")
    @Log(action = "分类管理公告", detail = "删除分类信息")
    public DataVo deleteCategories(@PathVariable Integer id) {
        boolean deleted = categoryService.removeById(id);
        return deleted ? DataVo.success("成功删除") : DataVo.fail("删除失败");
    }

    //批量删除分类信息
    @PostMapping("/deleteAllCategories")
    @Log(action = "分类管理公告", detail = "批量删除分类信息")
    public DataVo deleteAllCategories(@RequestBody List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return DataVo.fail("请传入要删除的分类ID");
        }
        boolean deleted = categoryService.removeByIds(ids);
        if (deleted) {
            return DataVo.success("批量删除成功");
        } else {
            return DataVo.fail("批量删除失败，部分或全部分类可能不存在");
        }
    }

    @PutMapping("/updateCategories")
    @Log(action = "分类管理公告", detail = "更新分类信息")
    public DataVo updateCategories(@RequestBody Category category) {
        if (category == null || category.getId() == null) {
            return DataVo.fail("分类ID不能为空");
        }
        //修改后更新创造时间
        category.setCreatedAt(new Date());
        boolean updated = categoryService.updateById(category);
        return updated ? DataVo.success("修改成功") : DataVo.fail("修改失败，分类可能不存在");
    }

    /**
     * 获取所有分类（不分页，用于下拉选择等场景）
     */
    @GetMapping("/getAllCategories")
    public DataVo getAllCategories() {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("sort");
        List<Category> categoryList = categoryService.list(queryWrapper);
        return DataVo.success(categoryList);
    }

    /**
     * 根据ID获取分类详情
     */
    @GetMapping("/{id}")
    public DataVo getCategoryById(@PathVariable Long id) {
        Category category = categoryService.getById(id);
        if (category == null) {
            return DataVo.fail("分类不存在");
        }
        return DataVo.success(category);
    }
}
